package com.freewater.javabase.demo.mutithread.synchronize;

import java.util.*;

public class TaskQueueDemo {

    public static void main(String[] args) throws InterruptedException {
        TaskQueue queue = new TaskQueue();
        List<Thread> getTaskThreads = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            Thread t = new Thread(() -> {
                while (true) {
                    try {
                        String task = queue.getTask();
                        System.out.println("Thread " + Thread.currentThread().getId() + " execute task: " + task);
                    } catch (InterruptedException e) {
                        break;
                    }
                }
            });
            t.start();
            getTaskThreads.add(t);
        }

        Thread addT = new Thread(() -> {
            Random r = new Random();
            for (int i = 0; i < 10; i++) {
                String task = "t_" + r.nextDouble();
                queue.addTask(task);
                System.out.println("Thread " + Thread.currentThread().getId() + " add Task: " + task);
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                }
            }
        });
        addT.start();
        addT.join();
        Thread.sleep(1000);
        for (Thread t : getTaskThreads) {
            t.interrupt();
        }
    }

    public static class TaskQueue {

        private Queue<String> queue = new LinkedList<>();

        public synchronized void addTask(String s) {
            queue.add(s);
            this.notifyAll();
        }

        public synchronized String getTask() throws InterruptedException {
            while (queue.isEmpty()) { // 使用while循环，每次拿到锁之后（进入方法拿到锁以及被唤醒后拿到锁）需要重新判断队列是不是空的
                this.wait();
            }
            return queue.remove();
        }
    }
}
